package org.deng.learn.jdbc;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * @Author DengLibin
 * @Date 19-4-8
 * @Time 上午10:29
 * @Desc JDBC事务
 */
public class JdbcTransaction {

    private final static String JDBC_URL = "jdbc:mysql://192.168.2.177:3306/denglibin?useSSL=false&useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai";
    private final static String USERNAME = "root";
    private final static String PASSWORD = "denglibin";
    JdbcTransaction() throws ClassNotFoundException {
        Class.forName("com.mysql.cj.jdbc.Driver"); //注册驱动
    }

    /**
     * 获取连接
     * @return
     * @throws SQLException
     */
    public Connection getConnection() throws SQLException {
        return DriverManager.getConnection(JDBC_URL,USERNAME, PASSWORD);
    }

    /**
     * 事务操作
     */
    public void commitTransaction(){
        Connection connection = null;
        PreparedStatement statement1 = null;
        PreparedStatement statement2 = null;
        try{
            connection = getConnection();
            connection.setAutoCommit(false);
            statement1 = connection.prepareStatement("UPDATE user set amount=amount-100 where name='张三'");
            statement2 = connection.prepareStatement("UPDATE user set amount=amount+100 where name='李四'");
            statement1.executeUpdate();
            statement2.executeUpdate();
            //int i = 3/0;
            connection.commit();
        }catch (Exception e){
            e.printStackTrace();
            try {
                System.out.println("回滚事务。。。。。。。。。。。。。。。。。");
                if(connection != null){
                    connection.rollback();
                }
            } catch (SQLException e1) {
                e1.printStackTrace();
            }
        }finally {
            try {
                if(statement1 != null){
                    statement1.close();
                }
                if(statement2 != null){
                    statement2.close();
                }
                if(connection != null){
                    connection.close();
                }
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }

    public  static  void  main(String[] args) throws ClassNotFoundException {
        JdbcTransaction jdbcTransaction = new JdbcTransaction();
        jdbcTransaction.commitTransaction();
    }

}
